import React from "react";
import { Link } from "react-router-dom";
import { Layout, Icon, Menu } from "antd";

import { useRouter } from "../hooks/useRouter";
import { useMenu } from "../hooks/useMenu";
import useAuth from "../hooks/useAuth";
import { checkAuth } from "../utils/checkAuth";

const { SubMenu } = Menu;

const Sider = ({ collapsed }) => {
  const { pathname } = useRouter();
  const { menu } = useMenu();
  const { loginUser } = useAuth();

  return (
    <Layout.Sider
      style={{
        overflow: "auto",
        height: "100vh",
        position: "sticky",
        left: 0,
        top: 0
      }}
      trigger={null}
      collapsible
      collapsed={collapsed}
    >
      <div className="logo" />
      <Menu
        theme="dark"
        defaultSelectedKeys={[pathname]}
        defaultOpenKeys={[pathname.substr(0, pathname.lastIndexOf("/"))]}
        mode="inline"
      >
        {menu.map(item => {
          return checkAuth({ auth: item.auth, loginUser })
            ? (item.children && item.children.length && (
                <SubMenu
                  key={item.path}
                  title={
                    <span>
                      <Icon type={item.icon} />
                      <span> {item.description} </span>
                    </span>
                  }
                >
                  {item.children.map(sub => {
                    return checkAuth({ auth: sub.name, loginUser }) ? (
                      <Menu.Item key={sub.path}>
                        <span> {sub.description} </span>
                        <Link to={sub.path} />
                      </Menu.Item>
                    ) : null;
                  })}
                </SubMenu>
              )) || (
                <Menu.Item key={item.path}>
                  <span>
                    <Icon type={item.icon} />
                    <span> {item.description} </span>
                  </span>
                  <Link to={item.path} />
                </Menu.Item>
              )
            : null;
        })}
      </Menu>
    </Layout.Sider>
  );
};

export default Sider;
